package com.cskaoyan.order.biz.handler;

import com.alibaba.fastjson.JSON;
import com.cskaoyan.mall.commons.exception.BaseBusinessException;
import com.cskaoyan.mall.commons.exception.BizException;
import com.cskaoyan.order.biz.context.CreateOrderContext;
import com.cskaoyan.order.biz.context.TransHandlerContext;
import com.cskaoyan.order.dal.entitys.Stock;
import com.cskaoyan.order.dal.persistence.StockMapper;
import com.cskaoyan.order.dto.CartProductDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @Description: 扣减库存处理器
 **/
@Component
@Slf4j
public class SubStockHandler extends AbstractTransHandler {

    @Autowired
    private StockMapper stockMapper;

    @Override
    public boolean isAsync() {
        return false;
    }

    @Override
    @Transactional
    public boolean handle(TransHandlerContext context) {

        //context向下转型
        CreateOrderContext createOrderContext = (CreateOrderContext) context;

        List<CartProductDto> dtoList = createOrderContext.getCartProductDtoList();
        List<Long> buyProductIds = createOrderContext.getBuyProductIds();
        // List<Long> buyProductIds1 =new ArrayList<>();
        //上下文转换时，没有ProductsId，手动赋值
        if (CollectionUtils.isEmpty(buyProductIds)){
           //
           //  for (CartProductDto cartProductDto : dtoList) {
           //      buyProductIds1.add(cartProductDto.getProductId());
           //  }
           // createOrderContext.setBuyProductIds(buyProductIds1);

            buyProductIds = dtoList.stream().map(u -> u.getProductId()).collect(Collectors.toList());

        }

        //对id进行排序
        buyProductIds.sort(Long::compareTo);

        //进行订单锁定
        List<Stock> stockList = stockMapper.findStocksForUpdate(buyProductIds);
        //如果库存列表为空，表示没有初始化，抛出异常
        if (CollectionUtils.isEmpty(stockList)){
            throw  new BizException("库存未初始化！");
        }
        //如果锁定商品数和商品id数不相等
        if (stockList.size() != buyProductIds.size()){
            throw  new BizException("部分库存未初始化！");
        }

        //扣减库存
        for (CartProductDto cartProductDto : dtoList) {
            Long productId = cartProductDto.getProductId();
            Long productNum = cartProductDto.getProductNum();

            //TODO productNum不能超过限购的数量
            Stock stock1 = stockMapper.selectStock(productId);

            if (productNum > stock1.getRestrictCount()){
                throw  new BizException("000015","超过库存限制！");
            }


            Stock stock = new Stock();
            stock.setItemId(productId);
            stock.setLockCount(productNum.intValue());
            stock.setStockCount(-productNum);
            stockMapper.updateStock(stock);
        }


        return true;
    }
}